﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Dting_Model;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;
using static User_manage.User_Lgon;

namespace Model_management
{
    public partial class Model_Management : UserControl
    {

        wirtePLCFrom _wirtePLCFrom;
        public string path;
        public string fileName;
        public DataTable _DataTable;//二维码信息
        public bool[] check_buf = new bool[8];
        public bool[] station_state = new bool[8];
        Model_ini_Class _ini_Class = new Model_ini_Class("Config\\sys_data.ini");
        public List<ModelManagement> modelManagements = new List<ModelManagement>();
        public string isName = "";//当前被选定的类
        public string subIsName = "";//当前被选定的子类
        public string isName_now = "";//当前使用类
        public string Barinfo_now = "";//当前使用条码信息名称
        public int int_ProductionCount = 0;//生产计数
        //事件
        public delegate void ModelWrite_Click(object sender, object dataname, object ModelName, object data, object Bar_data, object model_data);
        public event ModelWrite_Click _modelWrite_Click;

        //事件
        public delegate void WriteBarTest_Click(object sender);
        public event WriteBarTest_Click _writeBarTest_Click;

        //权限
        public H_Level User_Level;

        public Model_Management()
        {
            InitializeComponent();
            SetStyle(ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
            UpdateStyles();

            for (int i = 0; i < 8; i++)
            {
                string str = "station_" + (i + 1).ToString();
                bool.TryParse(_ini_Class.Read_Ini("sys_data", str), out check_buf[i]);
                (tabPage2.Controls[str] as CheckBox).Checked = check_buf[i];
            }
            ;
            data_Read();
            ;
            editing2_Read_Data(datatabel_editing2);
            ;

            //
            isName_now = _ini_Class.Read_Ini("sys_data", "Model_name");
            label1.Text = "当前使用机型类名：" + isName_now;

            Barinfo_now = _ini_Class.Read_Ini("sys_data", "Bar_name");
            label6.Text = "当前使用名称：" + Barinfo_now;

            datatabel_editing9._add_click += Datatabel_editing9__add_click;
            datatabel_editing9._delete_click += Datatabel_editing9__delete_click;

            datatabel_editing2._add_click += Datatabel_editing2__add_click;
            datatabel_editing2._delete_click += Datatabel_editing2__delete_click;

            datatabel_editing1._add_click += Datatabel_editing1__add_click;
            datatabel_editing1._delete_click += Datatabel_editing1__delete_click; ;

            //获取计划产量
            int.TryParse(_ini_Class.Read_Ini("sys_data", "ProductionCount"), out int_ProductionCount);
            ProductionCount.Text = int_ProductionCount.ToString();

            //获取条码名称
            get_BarcodeName();

            //获取打印名称
            get_PrintName();

            
            ;
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        private void UserControl1_Load(object sender, EventArgs e)
        {
            ;


        }

        //权限切换
        public void User_sw()
        {
            switch(User_Level)
            {
                case H_Level.None:
                    datatabel_editing9.ReadOnly = true;
                    datatabel_editing1.ReadOnly = true;
                    datatabel_editing2.ReadOnly = true;
                    break;

                case H_Level.管理员:
                    datatabel_editing9.ReadOnly = false;
                    datatabel_editing1.ReadOnly = false;
                    datatabel_editing2.ReadOnly = false;
                    break;
            }
        }

        private void tabPage9_Click(object sender, EventArgs e)
        {

        }

        //机型配置写入PLC
        private void button1_Click(object sender, EventArgs e)
        {
            if (User_Level == H_Level.生产员 || User_Level == H_Level.管理员)
            {
                _wirtePLCFrom = new wirtePLCFrom(this);
                _wirtePLCFrom.ShowDialog();
                _wirtePLCFrom.Dispose();
            }
            else
            {
                MessageBox.Show("权限错误，请切换为生产员权限/或更高的管理员权限", "错误提示");
                return;
            }

        }
        //写入PLC机型参数
        public void Model_Click(object sender)
        {
            try
            {
                string[] mame = sender as string[];
                string[] data_name = new string[3];
                string[] Bar_data = new string[5];
                if (mame != null)
                {
                    isName_now = isName;
                    data_name[0]= isName;
                    
                    ModelManagement data_buf = modelManagements.Find(x => x._className == isName);
                    if (data_buf != null)
                    {
                        DataRow[] drArr = data_buf._subClass._clasData.Select("配方ID='"+ mame[2]+"'");   //查询
                        if (drArr!=null && drArr.Length >0)
                        {
                            string[] model_data = drArr[0].ItemArray.Select(i => i.ToString()).ToArray();
                            data_name[1] = model_data[4];
                            data_name[2] = model_data[5];
                            
                            DataRow[] BardrArr = _DataTable.Select("名称='" + data_name[2] + "'");   //查询
                            if (BardrArr != null && BardrArr.Length >1)
                            {
                                string[] data = BardrArr[0].ItemArray.Select(i => i.ToString()).ToArray();
                                for (int h = 0; h < Bar_data.Length; h++)
                                    Bar_data[h] = data[h + 1];
                                _modelWrite_Click?.Invoke(station_state, data_name, mame, data, Bar_data ,model_data);
                            }
                            else
                            {
                                MessageBox.Show("报错：未请正确选择机型，请重新选择。", "提示");
                            }
                            
                        }
                        
                    }
                }
            }
            catch (Exception er)
            {
                MessageBox.Show("异常报错："+er.ToString(),"提示");
            }
        }

        //校验状态保存
        private void checkBox1_MouseClick(object sender, MouseEventArgs e)
        {

            CheckBox buf = sender as CheckBox;
            if (buf != null)
            {
                int station_sn = 0;
                int.TryParse(buf.Text.Substring(1, 1), out station_sn);


                if (User_Level == H_Level.管理员)
                {
                    if (buf.Checked)
                    {
                        buf.Text = "P" + station_sn + "_工位开启校验";
                        _ini_Class.Write_Ini("sys_data", buf.Name, buf.Checked.ToString());
                    }
                    else
                    {
                        buf.Text = "P" + station_sn + "_工位关闭校验";
                        _ini_Class.Write_Ini("sys_data", buf.Name, buf.Checked.ToString());
                    }
                }
                else
                {
                    MessageBox.Show("权限错误，请切换为管理员权限", "错误提示");
                    bool check_buf = false;
                    bool.TryParse(_ini_Class.Read_Ini("sys_data", buf.Name), out check_buf);
                    buf.Checked = check_buf;
                    return;
                }

            }
        }

        //删除2
        private void Datatabel_editing2__delete_click(object sender)
        {
            editing2_Save_Data(datatabel_editing2);
        }
        //添加2
        private void Datatabel_editing2__add_click(object sender)
        {
            
        }

        //每次编辑完成都保存一次
        private void datatabel_editing2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            editing2_Save_Data(datatabel_editing2);
           
        }
        //鼠标点击单元格事件
        private void datatabel_editing2_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView Grid = sender as DataGridView;
            if (Grid != null)
            {
                if (e.Button == MouseButtons.Right)
                {
                    ;
                }
                else
                {
                    if (e.RowIndex > -1 && e.ColumnIndex == -1)
                    {
                        string[] str = gridview_tobox(Grid, e.RowIndex, e.ColumnIndex);
                        if (str != null)
                        {
                            label5.Text = "名    称 ：" + str[0];
                            ;
                        }
                    }
                }
            }
        }

        public int editing2_Save_Data(DataGridView dataGridView)
        {
            try
            {
                _DataTable = GetDataGridView(dataGridView);

                if (Serialize(_DataTable, Application.StartupPath + "\\Config\\Code_parameters.config") == 0)
                {
                    //MessageBox.Show("数据保存成功！", "提示");
                }
                else
                {
                    //MessageBox.Show("数据保存失败！", "提示");
                }
                return 0;
            }
            catch (Exception er)
            {
                return 1;
            }
        }

        public int editing2_Read_Data(DataGridView dataGridView)
        {
            try
            {
                //读取设备数据
                _DataTable = Deserialize<DataTable>(Application.StartupPath + "\\Config\\Code_parameters.config");
                if (_DataTable != null)
                {
                    dataGridView.Rows.Clear();
                    GridviewShowDataTable(_DataTable, dataGridView);
                }
                return 0;
            }
            catch (Exception er)
            {
                return 1;
            }
        }
        private void datatabel_editing1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            datatabel_editing1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value="";
        }

        //删除9
        private void Datatabel_editing9__delete_click(object sender)
        {
            string[] buf = sender as string[];
            if (buf != null)
            {

                for (int i = 0; i < buf.Length; i++)
                {
                    var data_buf = modelManagements.Find(x => x._className == buf[i] || x._className == null);
                    if (data_buf != null)
                    {
                        int index = modelManagements.IndexOf(data_buf);
                        modelManagements.RemoveAt(index);
                    }
                }

                SubClass_Save();
            }

            ;
        }
        //添加9
        private void Datatabel_editing9__add_click(object sender)
        {
            isName = "";
            if (datatabel_editing9.ColumnCount > 0)
            {
                modelManagements.Add(new ModelManagement());

                //添加一行后进入编辑状态
                datatabel_editing9.CurrentCell = datatabel_editing9.Rows[datatabel_editing9.RowCount - 1].Cells[0];
                datatabel_editing9.BeginEdit(true);
            }
            ;
        }
        //删除1
        private void Datatabel_editing1__delete_click(object sender)
        {
            string[] buf = sender as string[];
            if (buf != null)
            {
                var data_buf = modelManagements.Find(x => x._className == isName || x._className == null);
                if (data_buf != null)
                {
                    for (int i = 0; i < buf.Length; i++)
                    {
                        for (int k = 0; k < data_buf._subClass._clasData.Rows.Count; k++)
                        {
                            if(data_buf._subClass._clasData.Rows[k][0].ToString()== buf[i])
                            {
                                data_buf._subClass._clasData.Rows.RemoveAt(k);
                            }
                        }                      
                    }
                }
                SubClass_Save();
            }
           
        }
        //添加1
        private void Datatabel_editing1__add_click(object sender)
        {
            ;
        }
        //Class
        ModelManagement buf;
        private void datatabel_editing9_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView Grid = sender as DataGridView;
            string[] str = gridview_tobox(Grid, e.RowIndex, e.ColumnIndex);
            if (str != null)
            {
                isName = str[0];
                mainClass_Save(datatabel_editing9, str[0],e);
                
                ;
            }
           
        }
        //鼠标点击单元格事件
        private void datatabel_editing9_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView Grid = sender as DataGridView;
            if (Grid != null)
            {
                if (e.Button == MouseButtons.Right)
                {
                    ;
                }
                else
                {
                    if (e.RowIndex>-1&&e.ColumnIndex == -1)
                    {
                        datatabel_editing1.Rows.Clear();
                        string[] str = gridview_tobox(Grid, e.RowIndex, e.ColumnIndex);
                        if (str != null)
                        {
                            isName = str[0];
                            //显示子类的数据
                            var buf = modelManagements.Find(x => x._className == isName);
                            int index = modelManagements.IndexOf(buf);
                            if (index >= 0)
                            {
                                GridviewShowDataTable(modelManagements[index]._subClass?._clasData, datatabel_editing1);
                            }
                            label2.Text = "机 型 型 号 ：" + str[0];
                            label3.Text = "配方组ID：" + str[1];

                            subIsName = "";
                            label4.Text = "配 方 ID：";
                            ;
                        }
                    }
                }
            }
        }

        //subClass
        private void datatabel_editing1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView Grid = sender as DataGridView;
            if (isName != string.Empty && Grid != null)
            {
                var buf = modelManagements.Find(x => x._className == isName);
                int index = modelManagements.IndexOf(buf);
                ModelManagement buf_Data = modelManagements[index];
                int vlaue = 0;
                int.TryParse((datatabel_editing1.Rows[e.RowIndex].Cells[0].Value != null) ? datatabel_editing1.Rows[e.RowIndex].Cells[0].Value.ToString() : "", out vlaue);
                buf_Data._classID = vlaue;
                buf_Data._subClass._clasData = GetDataGridView(datatabel_editing1);
                modelManagements[index] = buf_Data;
                SubClass_Save();
            }
            ;
        }
        private void datatabel_editing1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            
            DataGridView Grid = sender as DataGridView;
            if (Grid != null)
            {
                if (e.Button == MouseButtons.Right)
                {
                    ;
                }
                else
                {
                    if (e.RowIndex > -1 && e.ColumnIndex == -1)
                    {
                        string[] str = gridview_tobox(Grid, e.RowIndex, e.ColumnIndex);
                        if (str != null)
                        {
                            subIsName = str[0];
                            label4.Text = "配 方 ID：" + str[0];
                            ;
                        }
                    }
                }
            }
        }

        //保存机型数据  
        public int mainClass_Save(DataGridView dataGridView ,string strmain, DataGridViewCellEventArgs e)
        {
            try
            {
                //为空判断
                if (strmain==string.Empty)
                {
                    MessageBox.Show("名称不能为空，请检查！", "提示");
                    return 2;
                }

                //查找重复
                string str = "";
                bool str_state = not_User(dataGridView, strmain, ref str);
                if (!str_state)
                {
                    MessageBox.Show("有重复名称，请检查！", "提示");
                    dataGridView.CurrentCell = dataGridView.Rows[e.RowIndex].Cells[0];
                    dataGridView.BeginEdit(true);
                    return 2;
                }

                //记录数据
                int vlaue = 0;
                int index = e.RowIndex;
                if (index >= 0)
                {
                    buf = modelManagements[index];
                    buf._className = (dataGridView.Rows[e.RowIndex].Cells[0].Value != null) ? dataGridView.Rows[e.RowIndex].Cells[0].Value.ToString() : "";
                    int.TryParse((dataGridView.Rows[e.RowIndex].Cells[1].Value != null) ? dataGridView.Rows[e.RowIndex].Cells[1].Value.ToString() : "", out vlaue);
                    buf._classID = vlaue;
                    if (buf._subClass == null)
                    {
                        buf._subClass = new subClass();
                    }
                    modelManagements[index] = buf;
                }

                //删除空行
                for (int i = 0; i < dataGridView.RowCount; i++)
                {
                    str = (dataGridView.Rows[i].Cells[0].Value != null) ? dataGridView.Rows[i].Cells[0].Value.ToString() : string.Empty;
                    if (str == string.Empty)
                    {
                        try { dataGridView.Rows.RemoveAt(i); } catch {; }
                    }
                    str = modelManagements[i]._className;
                    if (str == string.Empty || str == null)
                    {
                        modelManagements.RemoveAt(i);
                    }
                }

                //保存到文件
                SubClass_Save();

                return 0;
            }
            catch (Exception er)
            {
                return 1;
            }

        }

        public int SubClass_Save()
        {
            try
            {
                //保存到文件
                if (Serialize(modelManagements, Application.StartupPath + "\\Config\\Model_Management.config") == 0)
                {
                    //MessageBox.Show("数据保存成功！", "提示");
                }
                else
                {
                    //MessageBox.Show("数据保存失败！", "提示");
                }
                return 0;
            }
            catch (Exception er)
            {
                return 1;
            }

        }

        //读取数据
        public void data_Read()
        {
            List<ModelManagement> buf = new List<ModelManagement>();
            try
            {
                modelManagements = Deserialize<List<ModelManagement>>(Application.StartupPath + "\\Config\\Model_Management.config");
                if (modelManagements != null)
                {
                    //显示到控件
                    datatabel_editing9.Rows.Clear();
                    for (int i = 0; i < modelManagements.Count; i++)
                    {
                        datatabel_editing9.Rows.Add();
                        datatabel_editing9.Rows[i].Cells[0].Value = modelManagements[i]._className;
                        datatabel_editing9.Rows[i].Cells[1].Value = modelManagements[i]._classID;
                    }
                    ;
                }

                return;
            }
            catch (Exception)
            {
                return;
            }
        }



        //返回鼠标点击行的所有数据
        private string[] gridview_tobox(DataGridView dataGridView,int Rows, int columns)
        {
            string[] tabel_str = new string[dataGridView.Columns.Count];
            try
            {
                if (Rows > -1)
                {
                    for (int j = 0; j < (dataGridView.Columns.Count); j++)
                    {
                        tabel_str[j] = Convert.ToString(dataGridView.Rows[Rows].Cells[j].Value);

                    }
                    return tabel_str;
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }

        }

        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch(tabControl2.SelectedIndex)
            {
                case 0:
                    get_BarcodeName();
                    get_PrintName();
                    break;
            }
        }

        //获取条码名称
        public void get_BarcodeName()
        {
            if (_DataTable != null && _DataTable.Rows.Count > 0)
            {
                DataGridViewComboBoxColumn cboCol = (DataGridViewComboBoxColumn)datatabel_editing1.Columns[5];
                cboCol.Items.Clear();
                for (int i = 0; i < _DataTable.Rows.Count; i++)
                {
                    cboCol.Items.Add(_DataTable.Rows[i][0].ToString());
                }
            }
        }

        //获取打印名称
        public void get_PrintName()
        {
            object buf = Deserialize<object>(Application.StartupPath + "\\Config\\PrintData.config");
 
            if (buf != null)
            {
                List<Barcod_data> _Barcod_data = ConvertToDesiredType(buf);
                if (_Barcod_data!=null && _Barcod_data.Count>0)
                {
                    DataGridViewComboBoxColumn cboCol = (DataGridViewComboBoxColumn)datatabel_editing1.Columns[4];
                    cboCol.Items.Clear();
                    for (int i = 0; i < _Barcod_data.Count; i++)
                    {
                        cboCol.Items.Add(_Barcod_data[i].Bar_name);
                    }
                }
                ;
            }
        }

        public List<Barcod_data> ConvertToDesiredType(object ListValue)
        {
            List<Barcod_data> returnList = new List<Barcod_data>();

            if (ListValue != null)
            {
                Barcod_data buf;
                foreach (var item in (IEnumerable<dynamic>)ListValue)
                {
                    buf = new Barcod_data();
                    buf.Bar_name = item.Bar_name;
                    buf.Bar_width = item.Bar_width;
                    buf.Bar_height = item.Bar_height;
                    buf.Bar_x = item.Bar_x;
                    buf.Bar_y = item.Bar_y;
                    buf.line_state = item.line_state;
                    buf.line_name = item.line_name;
                    buf.timer_state = item.timer_state;
                    buf.timer_Format = item.timer_Format;
                    buf.produce_state = item.produce_state;
                    buf.produce_sn = item.produce_sn;
                    buf.Incremental_state = item.Incremental_state;
                    buf.Incremental_sn = item.Incremental_sn;
                    buf.Incremental_Format = item.Incremental_Format;
                    returnList.Add(buf);
                }
            }

            return returnList;
        }

        //二维码信息写入
        private void button2_Click(object sender, EventArgs e)
        {
            if (label5.Text != string.Empty)
            {
                if (datatabel_editing2.SelectedRows.Count <= 0 || label5.Text == string.Empty)
                {
                    MessageBox.Show("未选择，请重新选择。", "提示");
                    return;
                }

                if (MessageBox.Show("当前选项 " + label5.Text.Trim().Replace(" ", "") + "  参数是否要写入PLC", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {

                    string[] stBuf = new string[6];

                    if (datatabel_editing2.SelectedRows.Count > 0)
                    {
                        var str = datatabel_editing2.SelectedRows[0];
                        stBuf[0] = str.Cells[0].FormattedValue.ToString();
                        stBuf[1] = str.Cells[1].FormattedValue.ToString();
                        stBuf[2] = str.Cells[2].FormattedValue.ToString();
                        stBuf[3] = str.Cells[3].FormattedValue.ToString();
                        stBuf[4] = str.Cells[4].FormattedValue.ToString();
                        stBuf[5] = str.Cells[5].FormattedValue.ToString();
                        this._writeBarTest_Click?.Invoke(stBuf);
                        ;
                    }
                    else
                    {
                        ;
                    }


                }
            }
            else
            {
                MessageBox.Show("当前选项为空不能写入，请选择需要写入的参数。", "提示");
            }

        }

        //计划产量
        private void textBox1_MouseUp(object sender, MouseEventArgs e)
        {


            string buf = "";
            try
            {
                buf = ProductionCount.Text.Trim();
                if (User_Level != H_Level.管理员)
                {
                    MessageBox.Show("权限错误，请切换为管理员权限", "错误提示");
                    ProductionCount.Text = buf;
                    return;
                }

                int data_buf = int.Parse(ProductionCount.Text.Trim());
                _ini_Class.Write_Ini("sys_data", "ProductionCount", data_buf.ToString());
            }
            catch (Exception er)
            {
                ProductionCount.Text = buf;
                MessageBox.Show("错误输入为非数字，请输入数字。");
            }
        }


        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        #region
        [Serializable]
        public class ModelManagement
        {
            public int _classID;
            public string _className;
            public subClass _subClass;
        }
        [Serializable]
        public class subClass
        {
            public int _classID;
            public DataTable _clasData;

            public subClass(int classID, DataTable clasData)
            {
                _classID = classID;
                _clasData = clasData;
            }
            public subClass()
            {
                _classID = 0;
                _clasData = null;
            }
        }

        ///条码参数
        [Serializable]
        public class Barcod_data
        {
            public string Bar_name;     //条码名称
            public int Bar_width;       //条码宽
            public int Bar_height;      //条码高度
            public int Bar_x;           //条码X
            public int Bar_y;           //条码Y

            public bool line_state;     //线条名称是否开启
            public string line_name;    //线条名称

            public bool timer_state;    //时间是否开启
            public string timer_Format; //时间格式

            public bool produce_state;      //生产批次是否开启
            public string produce_sn;       //批次

            public bool Incremental_state;      //是否递增累计
            public int Incremental_sn;          //累计计数
            public string Incremental_Format;   //批次格式

            public Barcod_data()
            {; }

            public Barcod_data(string str)
            { Bar_name = str; }
        }


        public int Serialize<T>(T source, string file_path)//序列化方法  
        {
            if (!typeof(T).IsSerializable)
            {
                //MessageBox.Show("类型必须是可序列化", "提示");
                return 1;
            }

            if (Object.ReferenceEquals(source, null))
            {
                //MessageBox.Show("实例不是相同的实例", "提示");
                return 2;
            }
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Create))//创建一个文件流，对文件进行写入
                {
                    BinaryFormatter bf = new BinaryFormatter();//使用CLR二进制格式器
                    bf.Serialize(fs, source); //序列化到硬盘
                    fs.Close();//关闭文件流
                }
                return 0;
            }
            catch
            {
                return 3;
            }
        }
        public T Deserialize<T>(string file_path)
        {
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Open))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    return (T)binaryFormatter.Deserialize(fs);
                }
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// DataTable表数据显示到DataGridview 必须要有列名并与DataTable对齐
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="dataGridView">DataGridView</param>
        /// <returns>true成功；false失败</returns>
        public int GridviewShowDataTable(DataTable table, DataGridView dataGridView)
        {
            try
            {
                if (table!=null && table.Rows.Count > 0)
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        dataGridView.Rows.Add();
                        dataGridView.Rows[i].Cells[0].Value = i;
                        for (int j = 0; j < (table.Columns.Count - 0); j++)
                        {
                            dataGridView.Rows[i].Cells[j + 0].Value = table.Rows[i][j + 0].ToString();//ItemArray
                            //Application.DoEvents();//可以交出控制权但是慢
                        }
                    }
                }

                return 0;
            }
            catch (Exception ex)
            { return 1; }

        }

        /// <summary>
        /// DataGridView导出为Datatable
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <returns>Datatable</returns>
        public DataTable GetDataGridView(DataGridView dgv)
        {
            DataTable dt = new DataTable();

            // 列强制转换
            for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn(dgv.Columns[count].HeaderText.ToString());
                dt.Columns.Add(dc);
            }

            // 循环行
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr = dt.NewRow();
                for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    //dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                    dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].FormattedValue);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

        //判断不能重复用户名
        public Boolean not_User(DataGridView dt, string str, ref string id)
        {
            try
            {
                int a = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string buf = (dt.Rows[i].Cells[0].Value != null) ? dt.Rows[i].Cells[0].Value.ToString() : "";
                    if (str == buf)
                    { a++; if (a > 1) { id = str; return false; } }
                }
            }
            catch { return false; }
            return true;
        }









        #endregion


    }
}
